#coding:utf-8
import socket
import json
from db.pack import *
from tools.enum_define import ENUMURLCODE

db_addr = ('121.199.9.188',55556)
BUFSIZE=1024


def request_db_param(query,dict_data):
    request_data = {}
    request_data["query"] = query   
    if(not isinstance(dict_data,dict)):
        return (ENUMURLCODE.db_datatype_error.value,"dict_data not python dict")
    request_data['data'] = dict_data
    request_str = json.dumps(request_data)
    return request_db(request_str)


#返回元组，
def request_db(data):
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.settimeout(4)
    try:
        s.connect(db_addr)
    except(Exception):
        ret = (ENUMURLCODE.db_conn_timeout.value,{'errcode':-1, 'errmsg':'connect failed'})
    else:
        send_data = enpack(data)
        try:
            s.send(send_data.encode('ISO-8859-1'))
            recv_data = s.recv(2).decode('ISO-8859-1')
            while(header != recv_data):
                recv_data = s.recv(2).decode('ISO-8859-1')
            data_len = s.recv(4).decode('ISO-8859-1')
            data_len = unpack_len(data_len)
            len_temp = 0
            feedback = b''
            while(len_temp!=data_len):
                feedback_temp=s.recv(data_len-len_temp)
                feedback += feedback_temp
                len_temp += len(feedback_temp)
        except(Exception):
            ret = (ENUMURLCODE.db_query_timeout.value, {'errcode':-1, 'errmsg':'timeout'})
        else:
            ret = (ENUMURLCODE.success.value,feedback.decode('utf-8'))
    s.close()
    return ret
